﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.UI.Views;
using StockFinder.DataAccess;
using StockFinder.Model;

namespace StockFinder.UI.Controllers
{
    public class JustBrokenOutResultsController
    {
        private readonly IBasicResultsView _View;
        private readonly ResultsDataAccess _ResultsDataAccess;
        private readonly IBDDataAccess _IBDDataAccess;

        public JustBrokenOutResultsController(IBasicResultsView view)
        {
            _View = view;

            _ResultsDataAccess = new ResultsDataAccess();
            _IBDDataAccess = new IBDDataAccess();

            _View.LoadResults += new EventHandler(_View_LoadResults);
        }

        void _View_LoadResults(object sender, EventArgs e)
        {
            DateTime runDate = _View.GetRunDate();

            //load results from dataaccess
            List<PriceAnalysisResult> results = _ResultsDataAccess.GetJustBrokenOutResultsForDate(runDate);

            //load the IBD ratings for each sybmol in the result
            List<IBDRatings> ibdRatings = _IBDDataAccess.GetAllIBDRatingsByDate(runDate);

            List<PriceAnalysisResultContainer> resultsContainers = new List<PriceAnalysisResultContainer>();

            IBDRatings ratingsMatch = null;
            PriceAnalysisResultContainer container = null;

            foreach (var result in results)
            {
                container = new PriceAnalysisResultContainer();
                resultsContainers.Add(container);
                container.PriceAnalysisResult = result;

                ratingsMatch = ibdRatings.Find(i => i.Symbol == result.SymbolName);

                if (ibdRatings != null)
                {
                    container.IBDRatings = ratingsMatch;
                }
            }

            _View.SetResults(resultsContainers.OrderBy(i => i.PriceAnalysisResult.DaysOfPrices));
        }
    }
}
